package wap.rockvilletech.portal;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

public class SystemProperty {
	
	private static final Logger log = Logger.getLogger(SystemProperty.class);
	private static Map<String, String> properties = new HashMap<String, String>();
	
	private static String loadProperty(String name) {
		String propVal = null;
		DBProc dbProc = DBProc.getInstance();
		Connection conn = null;
		try {
			conn = dbProc.getJNDIConnection();
			String query = "select name, value from system_property where name=?";
			java.sql.PreparedStatement pstmt = conn.prepareStatement(query);
			pstmt.setString(1, name);
			ResultSet rs = pstmt.executeQuery();
			if(rs.next()) {
				propVal = rs.getString("value");
				log.info("system property loaded, "+name+" = "+propVal);
			}
			rs.close();
			pstmt.close();
		}
		catch(Exception e) {
			log.error("Error loading property ["+name+"]",e);
		} finally {
			dbProc.closeJNDIConnection(conn);
		}
		return propVal;
	}
	
	public static String getProperty(final String propName) {		
		synchronized (properties) {
			String str = properties.get(propName);
			if(str == null) {			
				if((str = loadProperty(propName)) == null) {
					log.warn("no property found in database for ("+propName+")");
					str = "";
				}
				else {
					properties.put(propName, str);
				}
			}
			return str;
		}
	}
        public static boolean clearProperties() {
		synchronized (properties) {
			properties.clear();
			return properties.isEmpty();
		}
	}
}
